const userService = require('../service/user.service');
const errorTypes = require('../constants/error-types');
const md5password = require("../utils/password-handle");

// 验证用户
const verifyUser = async (ctx, next) => {
  // 1.获取用户名, 密码
  const { nickname, password } = ctx.request.body;
  // 2.判断用户名, 密码不为空
  if (!nickname || !password) {
    const error = new Error(errorTypes.NICKNAME_OR_PASSWORD_IS_REQUIRED);
    return ctx.app.emit('error', error, ctx);
  }
  // 3.判断用户名不重复
  const result = await userService.getUserByNickname(nickname);
  if (result.length > 0) {
    const error = new Error(errorTypes.USER_ALREADY_EXISTS);
    return ctx.app.emit('error', error, ctx);
  }
  // 4.验证通过
  await next();
}

// 密码加密
const handlePassword = async (ctx, next) => {
  let { password } = ctx.request.body;
  ctx.request.body.password = md5password(password);
  await next();
}

module.exports = {
  verifyUser,
  handlePassword
}
